package com.hxzy.commons.action;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hxzy.commons.helper.UploadHelper;
import com.hxzy.core.base.action.BaseAction;
import com.hxzy.core.utils.UUIDGenerator;

/**
 * 上传文件
 * @author Abdi
 * @description 
 * @created Oct 15, 2013 1:34:54 PM
 */
@Controller
@RequestMapping("/commons")
public class UploadAction extends BaseAction{
	@RequestMapping(value="/uploadSingleFile")
	public @ResponseBody String uploadFile(HttpServletRequest request,Model model){
		// ***************************  获取数据Demo ************************************* //
//		System.out.println("==========>>>>  " + request.getParameter("testKey")  + " +======="); //普通获取
//		try {
//			String testKey2 = URLDecoder.decode(request.getParameter("testKey2"), "utf-8"); // 中文获取
//			System.out.println("==========>>>>  " + testKey2  + " +=======");
//		} catch (UnsupportedEncodingException e1) {
//			e1.printStackTrace();
//			throw new RuntimeException();
//		}
		
		// 临时文件储存路径
		String tempFolder = UploadHelper.getTempFolderRealPath(request);
		// 获取文件列表
		List<FileItem> fileList = null;
		try {
			fileList = UploadHelper.getUploadFileList(request,UploadHelper.SIZE_THRESHOLD);
		} catch (FileUploadException e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
		
		// 处理保存文件
		Iterator<FileItem> it = fileList.iterator();
		JSONArray fileJsonArray = new JSONArray(); // 返回结果
		String realFileName = null; // 上传时文件名
		String randomFileName = null; // 保存时文件名
		while (it.hasNext()) {
			FileItem item = it.next();
			if (!item.isFormField()) {
				realFileName = item.getName();
				if (null == realFileName || "".equals(realFileName.trim())) {
					continue;
				}
				String nameSuffix = realFileName.substring(realFileName.lastIndexOf("."));
				randomFileName = tempFolder + UUIDGenerator.getUUID() + nameSuffix; // 文件名由UUID生成，保证不重复
				File tempFile = new File(randomFileName);
				try {
					// 写文件
					item.write(tempFile);
					
					// 返回处理后信息
					JSONObject fileJson = new JSONObject();
					fileJson.put("realname", realFileName);
					fileJson.put("filepath", randomFileName);
					fileJsonArray.add(fileJson);
				} catch (Exception e) {
					e.printStackTrace();
					throw new RuntimeException();
				}
			}
		}
		JSONObject result = new JSONObject();
		result.put("filelist", fileJsonArray);
		System.out.println("============== " + result.toString());
		// 数据返回形式，自行组织
		return "<script type='text/javascript' type='language'>parent.uploadCallback("+result.toString()+")</script>";
//		return result.toString();
	}
	
	@RequestMapping(value="/uploadMultiFiles",produces = {"application/text;charset=UTF-8"})
	public @ResponseBody String uploadMultiFiles(HttpServletRequest request,Model model){
		
		return null;
	}
}
